#!coding=utf8
from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from django.http import JsonResponse, StreamingHttpResponse
from django.contrib.auth import authenticate
from django.views.generic import View
from django.core.paginator import *
from django.utils.html import mark_safe
from django.db.models import Q
import json, xlwt, os, time
from ITAdmin import settings


from .models import *
from utils.download import *
from utils.constant import ACTIVED
from utils.view import get_params


# Create your views here.


class ServerView(View):
    '''服务器'''
    def get(self, request):
        '''查看服务器信息'''
        if request.user.is_authenticated():
            search, start, end, entry, num = get_params(request)
            context = {'services': ACTIVED,
                       'service': ACTIVED,
                       'entry': entry,
                       'search': '',
                       'table_class': mark_safe('table table-bordered'),
                       'table_id': 'server_table',
                       'table_title': u'服务器'}
            if not search:
                servers = Server.objects.all()
            else:
                servers = Server.objects.filter(Q(name__icontains=search)|
                                                Q(cpu__name__icontains=search)|
                                                Q(generatorroom__name__icontains=search)).all()
                context['search'] = context['search'] + 'top-search=' + search
                context['last_search'] = search
            if not servers.exists():
                return render(request, 'Assets/server.html', context=context)
            if start:
                time_start = datetime.strptime(start, "%Y-%m-%d")
                servers = servers.filter(add_time__gte=time_start)
                context['search'] = 'start=' + start + '&'
                context['start'] = start
            if  end:
                time_end = end + " 23:59:59"
                servers = servers.filter(add_time__lte=time_end)
                context['search'] = context['search'] + 'end=' + end + '&'
                context['end'] = end
            paginator = Paginator(servers, entry)
            servers = paginator.page(num)
            context['objects'] = servers
            return render(request, 'Assets/server.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        if request.user.is_authenticated():
            '''下载Server'''
            servers = Server.objects.all()
            search = request.POST.get('search')
            start = request.POST.get('start')
            end = request.POST.get('end')
            if search:
                servers = servers.filter(
                    Q(name__icontains=search)|
                    Q(cpu__name__icontains=search)|
                    Q(generatorroom__name__icontains=search))
            if start:
                time_start = datetime.strptime(start, "%Y-%m-%d")
                servers = servers.filter(add_time__gte=time_start)
            if end:
                time_end = datetime.strptime(end, "%Y-%m-%d")
                servers = servers.filter(add_time__lte=time_end)
            f = xlwt.Workbook()
            sheet1 = f.add_sheet(u'server', cell_overwrite_ok=True)
            rows = [[u'主机名', u'所在机房', u'内网IP', u'外网IP', u'内存', u'CPU型号', u'CPU内核数', u'硬盘', u'备注']]
            for server in servers:
                row = list()
                row.append(server.name)
                row.append(server.generatorroom.name)
                row.append(server.get_vlan_ip())
                row.append(server.get_wan_ip())
                row.append(server.memory)
                row.append(server.cpu.name)
                row.append(server.cpu_count*server.cpu.kernel)
                row.append(server.get_disks())
                row.append(server.description)
                rows.append(row)
            for i in xrange(len(rows)):
                row = rows[i]
                for j in xrange(len(row)):
                    sheet1.write(i, j, rows[i][j])
            file_name = u'服务器_' + str(time.time()) + '.xls'
            file_path = os.path.join(settings.DOWNLOAD_ROOT, file_name)
            f.save(file_path)
            return JsonResponse({'url': '/static/files/download/' + file_name})
        else:
            return HttpResponse(status=403)


class ServerInfoView(View):
    '''查看密码'''
    def post(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.view_password'):
                sid = request.POST.get('id')
                server = Server.objects.get(id=sid)
                return JsonResponse({'password': server.password, 'mysqlpwd': server.mysql_password})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponseRedirect('/')
    def get(self, request):
        return HttpResponse(status=404)


class RoomsView(View):
    def get(self, request):
        if request.user.is_authenticated():
            search, start, end, entry, num = get_params(request)
            context = {'services': mark_safe('class="active"'),
                       'room': mark_safe('class="active"'),
                       'search': '',
                       'table_class': mark_safe('table table-bordered'),
                       'entry': entry,
                       'table_title': u'IDC机房'}
            if not search:
                rooms = GeneratorRoom.objects.all()
            else:
                rooms = GeneratorRoom.objects.filter(Q(name__icontains=search) |
                                     Q(address__icontains=search) |
                                     Q(phone_num=search)).all()
                context['search'] = context['search'] + 'top-search=' + search
                context['last_search'] = search
            if not rooms.exists():
                return render(request, 'Assets/room.html', context=context)
            if start:
                time_start = datetime.strptime(start, "%Y-%m-%d")
                rooms = rooms.filter(add_time__gte=time_start)
                context['search'] = 'start=' + start + '&'
                context['start'] = start
            if  end:
                time_end = end + " 23:59:59"
                rooms = rooms.filter(add_time__lte=time_end)
                context['search'] = context['search'] + 'end=' + end + '&'
                context['end'] = end
            paginator = Paginator(rooms, entry)
            rooms = paginator.page(num)
            context['objects'] = rooms
            return render(request, 'Assets/room.html', context=context)
        else:
            return HttpResponseRedirect('/')

    def post(self, request):
        if request.user.is_authenticated():
            rooms = GeneratorRoom.objects.all()
            search = request.POST.get('search')
            start = request.POST.get('start')
            end = request.POST.get('end')
            if search:
                rooms = rooms.filter(
                    Q(name__icontains=search)|
                    Q(cpu__name__icontains=search)|
                    Q(generatorroom__name__icontains=search))
            if start:
                time_start = datetime.strptime(start, "%Y-%m-%d")
                rooms = rooms.filter(add_time__gte=time_start)
            if end:
                time_end = datetime.strptime(end, "%Y-%m-%d")
                rooms = rooms.filter(add_time__lte=time_end)
            f = xlwt.Workbook()
            sheet1 = f.add_sheet(u'IDC', cell_overwrite_ok=True)
            rows = [[u'机房名', u'地址', u'联系电话', u'服务器', u'服务器总数']]
            for room in rooms:
                row = list()
                row.append(room.name)
                row.append(room.address)
                row.append(room.phone_num)
                row.append(room.get_servers())
                row.append(room.servers.all().count())
                rows.append(row)
            for i in xrange(len(rows)):
                row = rows[i]
                for j in xrange(len(row)):
                    sheet1.write(i, j, rows[i][j])
            file_name = u'IDC_' + str(time.time()) + '.xls'
            file_path = os.path.join(settings.DOWNLOAD_ROOT, file_name)
            f.save(file_path)
            return JsonResponse({'url': '/static/files/download/' + file_name})
        else:
            return HttpResponse(status=403)


class AddServerView(View):
    def get(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.add_server'):
                rooms = GeneratorRoom.objects.all()
                cpus = Cpu.objects.all()
                return render(request, 'Assets/addserver.html',
                              {'services': mark_safe('class="active"'),
                               'service': mark_safe('class="active"'),
                               'rooms': rooms,
                               'cpus': cpus,
                               'disks': 'var disks = new Array();',
                               'ips': 'var ips = new Array();'})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponse(status=403)

    def post(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.add_server'):
                ips = json.loads(request.POST.get('ips'))
                disks = json.loads(request.POST.get('disks'))
                info = json.loads(request.POST.get('info'))
                try:
                    if request.user.has_perm('Assets.view_password'):
                        server = Server(name=info['name'],
                                        cpu_id=int(info['cpu_id']),
                                        memory=int(info['memory']),
                                        cpu_count=int(info['cpu_count']),
                                        generatorroom_id=int(info['generatorroom_id']),
                                        ssh_port=int(info['ssh_port']),
                                        add_time=datetime.strptime(info['add_time'], "%Y-%m-%d"),
                                        password=info['password'],
                                        mysql_password=info['mysql_password'],
                                        description=info['description'])
                    else:
                        server = Server(name=info['name'],
                                        cpu_id=int(info['cpu_id']),
                                        memory=int(info['memory']),
                                        cpu_count=int(info['cpu_count']),
                                        generatorroom_id=int(info['generatorroom_id']),
                                        ssh_port=int(info['ssh_port']),
                                        description=info['description'],
                                        add_time=datetime.strptime(info['add_time'], "%Y-%m-%d"))
                    server.save()
                    for disk in disks:
                        d = Disk(name=disk['name'],
                                 mount_path=disk['mount_path'],
                                 size=int(disk['size']),
                                 server_id=server.id)
                        d.save()
                    for ip in ips:
                        i = IpAddress(ip=ip['ip'],
                                      type=ip['type'],
                                      server_id=server.id)
                        i.save()
                except Exception as e:
                    return JsonResponse({'status': 0, 'msg': e.message.encode('utf8')})
                return JsonResponse({'status': 1})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponse(status=403)


class DeleteServerView(View):
    def post(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.delete_server'):
                server_id_list = json.loads(request.POST.get('ids'))
                server_id_list = list(map(int, server_id_list))
                try:
                    for server_id in server_id_list:
                        Disk.objects.filter(server_id=server_id).delete()
                        IpAddress.objects.filter(server_id=server_id).delete()
                    Server.objects.filter(id__in=server_id_list).delete()
                    return JsonResponse({"status": 1})
                except Exception as e:
                    return JsonResponse({'status': 0})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponse(status=403)


class ChangeServerView(View):
    def get(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.change_server'):
                server_id = int(request.GET.get('id'))
                server = Server.objects.get(id=server_id)
                disks = Disk.objects.filter(server_id=server_id).all()
                ips = IpAddress.objects.filter(server_id=server_id).all()
                rooms = GeneratorRoom.objects.all()
                cpus = Cpu.objects.all()
                return render(request, 'Assets/addserver.html',
                              {'services': mark_safe('class="active"'),
                               'service': mark_safe('class="active"'),
                               'rooms': rooms,
                               'cpus': cpus,
                               'disks': disks,
                               'ips': ips,
                               'server':server,
                               'type': 1,
                               'server_id': server_id})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponse(status=403)

    def post(self, request):
        if request.user.is_authenticated():
            if request.user.has_perm('Assets.change_server'):
                server_id = request.POST.get('server_id')
                ips = json.loads(request.POST.get('ips'))
                disks = json.loads(request.POST.get('disks'))
                info = json.loads(request.POST.get('info'))
                try:
                    Server.objects.filter(id=server_id).update(name=info['name'],
                                    cpu_id=int(info['cpu_id']),
                                    memory=int(info['memory']),
                                    cpu_count=int(info['cpu_count']),
                                    generatorroom_id=info['generatorroom_id'],
                                    ssh_port=int(info['ssh_port']),
                                    add_time=datetime.strptime(info['add_time'], "%Y-%m-%d"),
                                    password=info['password'],
                                    mysql_password=info['mysql_password'],
                                    description=info['description'])
                    disk = Disk.objects.filter(server_id=server_id).delete()
                    IpAddress.objects.filter(server_id=server_id).delete()
                    for disk in disks:
                        if disk.has_key('id'):
                            d = Disk(id=int(disk['id']),
                                     name=disk['name'],
                                     mount_path=disk['mount_path'],
                                     size=int(disk['size']),
                                     server_id=server_id)
                        else:
                            d = Disk(name=disk['name'],
                                     mount_path=disk['mount_path'],
                                     size=int(disk['size']),
                                     server_id=server_id)
                        d.save()
                    for ip in ips:
                        if ip.has_key('id'):
                            i = IpAddress(id=int(ip['id']),
                                          ip=ip['ip'],
                                          type=ip['type'],
                                          server_id=server_id)
                        else:
                            i = IpAddress(ip=ip['ip'],
                                          type=ip['type'],
                                          server_id=server_id)
                        i.save()
                    return JsonResponse({"status": 1})
                except Exception as e:
                    return JsonResponse({'status': 0, 'msg': e.message})
            else:
                return HttpResponse(status=403)
        else:
            return HttpResponse(status=403)
